<template>
  <el-dialog
    top="30px"
    width="1100px"
    append-to-body
    title="选择新增机构"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :inline="true">
      <el-form-item>
        <select-address
          v-model="params.address_code"
          auto-top
          clearable
          @change="getData()"
          placeholder="地址查询"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.agency_name"
          @keyup.enter.native="getData()"
          placeholder="机构名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()" :loading="loading">查询</el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      class="table-sm"
      ref="multipleTable"
      name="table"
      v-loading="loading"
      :columns="tableColumns"
      :row-key="getRowKeys"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:address="scope">
        <div class="text-truncate" :title="scope.row.address">{{ scope.row.address }}</div>
      </template>
    </c-table>
    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <el-button @click="clearAll" class="mt-1">清空选项</el-button>
    <div class="text-center mt-5">
      <el-button type="primary" class="btn-long" @click="onSubmit">保存</el-button>
      <el-button class="btn-long" @click="beforeClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import SelectAddress from '@/components/select/SelectAddress'
import { mapGetters } from 'vuex'
export default {
  components: {
    SelectAddress,
  },
  props: {
    visible: Boolean,
  },
  data() {
    return {
      params: {
        index: 1,
        size: 10,
        'agency_type.eq': 2,
        address_code: '',
        agency_name: '',
        groupFields: 'agency_id',
        fields: ['agency_name', 'agency_id', 'address', 'contact', 'mobile_no'],
      },
      order: {
        agency_create_time: 'desc',
      },
      loading: false,
      tableData: [],
      totalCount: 0,
      tableName: 'credit_agency_access_select_view',
      tableColumns: [
        { attrs: { label: '选择', type: 'selection', align: 'center', reserveSelection: true } },
        { attrs: { label: '机构名称', prop: 'agency_name' } },
        { attrs: { label: '地址', prop: 'address' }, slot: 'address' },
        { attrs: { label: '联系人', prop: 'contact' } },
        { attrs: { label: '联系电话', prop: 'mobile_no' } },
      ],
      selectData: [],
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user']),
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    orgRegionLever() {
      return this.user.orgRegionLever
    },
  },

  created() {
    this.params['orWhere.service_id.neq'] = this.clientId
    this.params['orWhere.service_id.is'] = 'null'
    // this.params['access_agency_lever.gt'] = this.orgRegionLever
    this.params.address_code = this.queryAddressCode
    this.getData()
  },
  methods: {
    onSubmit() {
      if (!this.selectData.length) {
        return this.$message.warning('请先选择需要新增的担保联盟')
      }
      const name = []
      const data = []
      this.selectData.forEach(item => {
        name.push(item.agency_name)
        data.push({
          service_id: this.clientId,
          access_agency_id: item.agency_id,
          access_status: 0,
        })
      })
      this.$msgbox({
        title: '提示',
        message: `确认新增机构:  ${name.join('，')} ？`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonText = '操作中...'
            instance.confirmButtonLoading = true
            await this.$api
              .addBatch(this.$serviceName, 'credit_agency_access', data)
              .then(() => {
                this.$message.success('添加成功')
                this.getData()
                this.beforeClose()
                this.$emit('success', true)
              })
              .catch(() => {
                this.$message.error('添加失败')
              })
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            done()
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
    clearAll() {
      this.selectData = []
      const $tableRef = this.$refs.multipleTable.$refs.table
      $tableRef.clearSelection()
    },
    beforeClose() {
      this.clearAll()
      this.$emit('update:visible', false)
    },
    getRowKeys(row) {
      return row.agency_id
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = (res && res.data) || {}
          this.tableData = data.data || []
          this.totalCount = data.totalCount
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSelectionChange(select) {
      this.selectData = select
    },
  },
}
</script>
<style lang="scss" scoped></style>
